<?php
declare (strict_types = 1);

namespace app\admin\business;

use think\Exception;
use think\facade\Log;

class Category {

    protected $model = null;

    public function __construct() {
        $this->model = new \app\model\mysql\Category();
    }

    public function save($data) : bool {
        $id = isset($data["id"]) ? $data["id"] : 0;
        if (isset($data["id"])) {
            unset($data["id"]);
        }

        $result = false;
        try{

            if ($data["pid"] <= 0) {
                $data["path"] = "0/";
            }else{
                $pCategory = $this->model->find($data["pid"]);
                $data["path"] = $pCategory->path . $data["pid"] . "/";
            }

            if ($id <= 0) {
                $result = $this->model->save($data);
            }else{
                $result = $this->model->where("id", $id)->save($data);
            }
        }catch (Exception $e){
            Log::error($e->getMessage());
            return false;
        }

        return $result;
    }

    public function updateById($id = 0, $data = []) : bool {
        if ($id <= 0 || empty($data)) {
            return true;
        }
        $result = false;
        try{
            $result =  $this->model->updateById($id, $data);
        }catch (Exception $e){
            Log::error($e->getMessage());
            return false;
        }

        return $result;
    }

    public function deleteById($id, $operator) : bool {
        if ($id <= 0) {
            return true;
        }
        $result = false;
        try{
            $result = $this->model->deleteById($id, $operator);
        }catch (Exception $e){
            Log::error($e->getMessage());
            return false;
        }

        return $result;
    }
}